<template>
  <div class="search-container">
    <ul class="breadcrumb">
      <li>{{$t('message.searchResult')}} >&nbsp;</li>
      <li class="chooseBrand" v-for="item in chooseBrandObj">{{ item.name }} <span class="closeTab" @click="closeTab(item)">X</span></li>
      <li>
        <span class="goods-list-length" v-if="status === 'null'"> 0 </span>
        <span class="goods-list-length" v-else> {{ total }} </span>
        {{$t('message.relatedProduct')}}
      </li>
      <!--<li><span class="goods-list-length" v-if="status === 'null'"> 0 </span>{{$t('message.relatedProduct')}}</li>-->
    </ul>
    <div class="loading" v-if="status === 'loading'">
    	<v-loading></v-loading>
    </div>
    <template v-if="status === 'complete'">
    	<div class="search">
	      <table>
	        <tr>
	          <td class="table-title table-brand">{{$t('message.brand')}}</td>
	          <td>
	          	<v-checkbox class="table-item" @on-choose-checkbox="onChooseCheckbox" :brandItem="item" v-for="(item, index) in chooce.brand" :key="index" :is-click-tab="isClickTab"></v-checkbox>
	          </td>
	        </tr>
	      </table>
	    </div>
	    <div class="result">
	      <div class="detail-look">
	        <v-sider :products="lookProduct">{{$t('message.goodRecommend')}}</v-sider>
	      </div>
	      <div class="result-container">
		    	<ul class="result-top">
		    		<li class="result-comprehensive" :class="{ 'comprehensive': sort === 'comprehensive' }" @click="orderByComprehensive">{{$t('message.comprehensiveRanking')}}</li>
		    		<li class="result-sale" :class="[{ 'sale': sort === 'sale' }, saleOrder]" @click="orderBySale">{{$t('message.saleNum')}}<i></i></li>
		    		<li class="result-price" :class="[{ 'price': sort === 'price' }, priceOrder]" @click="orderByPrice">{{$t('message.price')}}<i></i></li>
		    		<li class="result-input-group" :class="{ 'result-input-focus': isFocusPriceRange }" @mouseenter="onFocusPriceRange" @mouseleave="onBlurPriceRange">
		    			<input v-model="minPrice" @keyup="selectNumber('minPrice')" type="text" class="result-input" :placeholder="$t('message.currencySymbol')" />
		    			<input v-model="maxPrice" @keyup="selectNumber('maxPrice')" type="text" class="result-input result-input-right" :placeholder="$t('message.currencySymbol')" />
		    			<button type="button" class="result-btn" @click="getPrice" v-if="isFocusPriceRange" :disabled="disabled" :class="{'not-allow' : disabled}">{{$t('message.yes')}}</button>
		    		</li>
		    	</ul>
		    	<div class="list-loading" v-if="listStatus === 'loading'">
		    		<v-loading></v-loading>
		    	</div>
		    	<template v-if="listStatus === 'complete'">
		    	  <div class="result-list">
              <item class="search-item" :class="{ 'search-no-right': index % 4 === 3}" :product="item" v-for="(item , index) in list" :key="index"></item>
            </div>
            <div class="pager">
              <v-pager @change-page="changePaged" :activeIndex="nowPage" :pageNum="allPage" :total="total"></v-pager>
            </div>
		    	</template>
		    	<div class="search-price" v-if="listStatus === 'null'">
		    		<div class="search-price-img"></div>
		    		<div class="search-null-title">
		    			{{ $t('message.noSearchTitle') }}
		    		</div>
		    		<div class="search-null-tip">
		    	    {{ $t('message.noSearchTip') }}
            </div>
		    	</div>
	      </div>
	    </div>
	    <!--猜你喜欢-->
			<div class="guess">
				<guess :products="products"></guess>
			</div>
    </template>
		<div class="search-null" v-if="status === 'null'">
			<div class="search-null-img"></div>
			<div class="search-null-title">
				{{ $t('message.sorry1') }}“<span>{{ keyWord }}</span>”{{ $t('message.sorry2') }}
			</div>
			<div class="search-null-tip">
				{{ $t('message.dontWorry') }}
			</div>
			<div class="recommend">
				<guess :products="products">{{ $t('message.goodRecommend') }}</guess>
			</div>
		</div>
  </div>
</template>

<script>
import VLoading from '@/components/base/VLoading'
import VCheckbox from '@/components/base/VCheckbox'
import Item from '@/components/base/VProductItemDetail'
import VPager from '@/components/base/VPager'
import Guess from '@/components/detail/DetailGuess'
import VSider from '@/components/base/VSider'

export default {
  name: 'Search',
  components: {
    VLoading,
    VCheckbox,
    Item,
    VPager,
    Guess,
    VSider
  },
  data () {
    return {
      status: 'loading',
      listStatus: 'complete',
      id: this.$route.query.id || '',
      getMinPrice: null,
      getMaxPrice: null,
      minPrice: null,
      maxPrice: null,
      chooseBrandId: [],
      chooseBrandObj: [],
      isClickTab: {},
      allPage: 1,
      nowPage: 1,
      total: 0,
      lookProduct: [],
      isFocusPriceRange: false,
      chooce: {
        brand: []
      },
      list: [],
      products: [],
      disabled: true
    }
  },
  watch: {
    '$route' (to, from) {
      if (to.query.id) {
        this.id = to.query.id
        if (!this.$route.query.sort) {
          this.toTypeSearch()
        }
      } else {
        this.id = ''
        if (!this.$route.query.sort) {
          this.status = 'loading'
          this.minPrice = ''
          this.maxPrice = ''
          this.chooseBrandObj = []
          this.chooseBrandId = []
          this.init()
        }
      }
    },
    maxPrice () {
      if (parseInt(this.maxPrice) > parseInt(this.minPrice)) {
        this.disabled = false
      } else {
        this.disabled = true
      }
    },
    minPrice () {
      if (parseInt(this.maxPrice) > parseInt(this.minPrice)) {
        this.disabled = false
      } else {
        this.disabled = true
      }
    }
  },
  computed: {
    isType () {
      if (this.chooseBrandId.length === 0) {
        if (this.id) {
          return 'goods_class_id'
        } else {
          return 'goods_name'
        }
      } else {
        return 'deal_loan_type'
      }
    },
    keyWord () {
      return this.$route.query.keyWord
    },
    sort () {
      let sort = this.$route.query.sort || 'comprehensive'
      return sort
    },
    saleOrder () {
      let saleOrder = this.$route.query.saleOrder || 'desc'
      return saleOrder
    },
    priceOrder () {
      let priceOrder = this.$route.query.priceOrder || 'asc'
      return priceOrder
    }
  },
  methods: {
    // 过滤非数字
    selectNumber (val) {
      if (typeof this[val] === 'string') {
        this[val] = this[val].replace(/\D/g, '')
      }
    },
    //  点击最小价格和最大价格的确定按钮
    getPrice () {
      this.getMinPrice = this.minPrice
      this.getMaxPrice = this.maxPrice
      this.judgeParams()
    },
    //    分页
    changePaged (val) {
      this.nowPage = val
      this.judgeParams()
      document.documentElement.scrollTop = 240
      document.body.scrollTop = 240
    },
    // 点击综合排序，销量，价格时，判断传给服务器的参数类型
    judgeParams () {
      if (this.sort === 'comprehensive') {
        this.switchCondition('sort', 'sort')
      } else if (this.sort === 'sale') {
        if (this.$route.query.saleOrder === 'desc') {
          this.switchCondition('sales_volume_sort', 'diminish')
        } else if (this.$route.query.saleOrder === 'asc') {
          this.switchCondition('sales_volume_sort', 'increase')
        }
      } else if (this.sort === 'price') {
        if (this.$route.query.priceOrder === 'desc') {
          this.switchCondition('base_price_sort', 'diminish')
        } else if (this.$route.query.priceOrder === 'asc') {
          this.switchCondition('base_price_sort', 'increase')
        }
      }
    },
    //  点击综合排序，销量，价格按钮后，执行此函数
    switchCondition (paramsName, paramsVal) {
      this.listStatus = 'loading'
      this.$ajax.goodsTypeSearch({
        type: this.isType,
        page: this.nowPage,
        number: 40,
        key_word: this.keyWord,
        goods_class_id: this.$route.query.id,
        min_price: this.minPrice,
        max_price: this.maxPrice,
        goods_class: this.chooseBrandId,
        [paramsName]: paramsVal
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.data.content
          this.allPage = res.data.page_count
          this.total = res.data.item_count
          this.listStatus = 'complete'
        } else if (res.code === 202) {
          console.log('请求数据失败数据为空')
          this.listStatus = 'null'
          this.list = []
        }
      })
    },
//    点击tab的X符号时
    closeTab (item) {
      this.isClickTab = item
    },
  //  选择品牌复选框时，执行此函数
    onChooseCheckbox (val, itemObj) {
      this.nowPage = 1  //  选中或者取消复选框时，都是从第一页开始加载数据
      if (val) {
        this.chooseBrandObj.push(itemObj)
        this.chooseBrandId.splice(0)
      } else {
        let i = this.chooseBrandObj.indexOf(itemObj)
        this.chooseBrandObj.splice(i, 1)
        this.chooseBrandId.splice(0)
      }
//      把id值传给服务器
      for (let j = 0; j < this.chooseBrandObj.length; j++) {
        this.chooseBrandId.push(this.chooseBrandObj[j].id)
      }
      if (this.sort === 'comprehensive') {  //  综合排序
        this.getGoodsList('sort', 'sort')
      } else if (this.sort === 'sale') {    //  销量
        if (this.$route.query.saleOrder === 'desc') {
          this.getGoodsList('sales_volume_sort', 'diminish')
        } else if (this.$route.query.saleOrder === 'asc') {
          this.getGoodsList('sales_volume_sort', 'increase')
        }
      } else if (this.sort === 'price') {  //  价格
        if (this.$route.query.priceOrder === 'desc') {
          this.getGoodsList('base_price_sort', 'diminish')
        } else if (this.$route.query.priceOrder === 'asc') {
          this.getGoodsList('base_price_sort', 'increase')
        }
      }
    },
  //  确定了品牌列表后执行此函数
    getGoodsList (paramsName, paramsVal) {
      this.listStatus = 'loading'
      this.$ajax.goodsTypeSearch({
        type: this.isType,
        page: this.nowPage,
        number: 40,
        key_word: this.keyWord,
        goods_class_id: this.$route.query.id,
        min_price: this.getMinPrice,
        max_price: this.getMaxPrice,
        goods_class: this.chooseBrandId,
        [paramsName]: paramsVal
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.data.content
          this.allPage = res.data.page_count
          this.total = res.data.item_count
          this.listStatus = 'complete'
          //        商品推荐
          this.$ajax.guessYouLike(res.data.content[0].id, 'recommend').then((res) => {
            if (res.code === 200) {
              if (this.list.length <= 8) {
                res.data.splice(2)
                this.lookProduct = res.data
              } else {
                this.lookProduct = res.data
              }
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
        } else if (res.code === 202) {
          this.listStatus = 'null'
          this.total = 0
          console.log('请求数据失败数据为空')
        }
      })
    },
    orderByComprehensive () {
      if (this.sort !== 'comprehensive') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'comprehensive'
          }
        })
        // 点击综合排序
        this.switchCondition('sort', 'sort')
      }
    },
    orderBySale () {
      if (this.sort !== 'sale' && this.saleOrder === 'desc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'sale',
            saleOrder: 'desc'
          }
        })
        //  点击销量
        this.switchCondition('sales_volume_sort', 'diminish')
      } else if (this.sort === 'sale' && this.saleOrder === 'desc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'sale',
            saleOrder: 'asc'
          }
        })
        // 点击销量
        this.switchCondition('sales_volume_sort', 'increase')
      } else if (this.sort === 'sale' && this.saleOrder === 'asc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'sale',
            saleOrder: 'desc'
          }
        })
        // 点击销量
        this.switchCondition('sales_volume_sort', 'diminish')
      }
    },
    orderByPrice () {
      if (this.sort !== 'price' && this.priceOrder === 'asc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'price',
            priceOrder: 'asc'
          }
        })
        // 点击价格
        this.switchCondition('base_price_sort', 'increase')
      } else if (this.sort === 'price' && this.priceOrder === 'desc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'price',
            priceOrder: 'asc'
          }
        })
        //        点击价格
        this.switchCondition('base_price_sort', 'increase')
      } else if (this.sort === 'price' && this.priceOrder === 'asc') {
        this.$router.push({
          path: '/search',
          query: {
            keyWord: this.keyWord,
            id: this.id,
            sort: 'price',
            priceOrder: 'desc'
          }
        })
        //        点击价格
        this.switchCondition('base_price_sort', 'diminish')
      }
    },
    onFocusPriceRange () {
      this.isFocusPriceRange = true
    },
    onBlurPriceRange () {
      this.isFocusPriceRange = false
    },
  //  点击导航条链接
    toTypeSearch () {
      this.nowPage = 1
      this.status = 'loading'
      this.listStatus = 'complete'
      this.minPrice = ''
      this.maxPrice = ''
      this.chooseBrandObj = []
      this.chooseBrandId = []
      this.$ajax.goodsTypeSearch({
        type: 'goods_class_id',
        page: this.nowPage,
        number: 40,
        key_word: this.keyWord,
        goods_class_id: this.$route.query.id,
        sort: 'sort'
      }).then((res) => {
        if (res.code === 200) {
          this.chooce.brand = res.data.goods_class
          this.list = res.data.content
          this.allPage = res.data.page_count
          this.total = res.data.item_count
          this.status = 'complete'
          // 商品推荐
          this.$ajax.guessYouLike(res.data.content[0].id, 'recommend').then((res) => {
            if (res.code === 200) {
              if (this.list.length <= 8) {
                res.data.splice(2)
                this.lookProduct = res.data
              } else {
                this.lookProduct = res.data
              }
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
          //  猜你喜欢
          this.$ajax.guessYouLike(res.data.content[0].id, 'like').then((res) => {
            if (res.code === 200) {
              this.products = res.data
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
        } else if (res.code === 202) {
          this.status = 'null'
          console.log('请求数据失败数据为空')
          // 商品推荐
          this.$ajax.productRecommend().then((res) => {
            if (res.code === 200) {
              this.products = res.data
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
        }
      })
    },
  //  页面加载时
    init () {
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      this.$router.push({path: '/search', query: {keyWord: this.keyWord, id: this.id}})
      this.$ajax.goodsTypeSearch({
        type: this.isType,
//        page: this.nowPage,
        page: 1,
        number: 40,
        key_word: this.keyWord,
        goods_class_id: this.$route.query.id,
        sort: 'sort'
      }).then((res) => {
        if (res.code === 200) {
          this.chooce.brand = res.data.goods_class
          this.list = res.data.content
          this.allPage = res.data.page_count
          this.total = res.data.item_count
          this.status = 'complete'
          // 商品推荐
          this.$ajax.guessYouLike(res.data.content[0].id, 'recommend').then((res) => {
            if (res.code === 200) {
              if (this.list.length <= 8) {
                res.data.splice(2)
                this.lookProduct = res.data
              } else {
                this.lookProduct = res.data
              }
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
          //  猜你喜欢
          this.$ajax.guessYouLike(res.data.content[0].id, 'like').then((res) => {
            if (res.code === 200) {
              this.products = res.data
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
        } else if (res.code === 202) {
          this.status = 'null'
          console.log('请求数据失败数据为空')
          // 商品推荐
          this.$ajax.productRecommend().then((res) => {
            if (res.code === 200) {
              this.products = res.data
            } else if (res.code === 202) {
              console.log('请求数据失败数据为空')
            }
          })
        }
      })
    }
  },
  created () {
    this.init()
  }
}
</script>
<style scoped>
  .goods-list-length {
    color: #FF600A;
  }

.breadcrumb {
   padding-top: 24px;
   overflow: hidden;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.breadcrumb li {
  float: left;
  height: 20px;
  line-height: 20px;
  font-size: 14px;
  color: #666666;
}
.breadcrumb .chooseBrand {
  border: 1px solid #E0E0E0;
  margin-top: -4px;
  margin-bottom: 12px;
  margin-right: 8px;
  padding: 4px 8px;
  cursor: pointer;
}
  .breadcrumb li:last-child {
    margin-top: 1px;
  }
  .breadcrumb .chooseBrand .closeTab{
    color: #E0E0E0;
    font-weight: bold;
    margin-left: 5px;
  }
  .breadcrumb .chooseBrand:hover {
    border: 1px solid #FF600A;
  }
  .breadcrumb .chooseBrand:hover .closeTab{
    color: #FF600A;
  }

.search-container {
	width: 1200px;
	margin: 0 auto;
	padding-bottom: 40px;
}

.search {
	margin-top: 24px;
}

.search table {
	width: 100%;
	border-collapse: collapse;
}

.search table, th, td {
	border: 1px solid #e0e0e0;
}

.search tr {
	/*height: 52px;*/
}

.search td {
	height: 20px;
	line-height: 20px;
	padding: 10px 24px;
}

.table-brand {
	vertical-align: top;
}

.table-title {
	width: 150px;
	background-color: #f7f7f7
}

.table-item {
	float: left;
	margin-right: 60px;
	padding: 6px 0;
}

.result {
	margin-top: 24px;
	overflow: hidden;
}

.detail-look {
  width: 200px;
  float:left;
}

.result-container {
	float: left;
	margin-left: 22px;
}

.result-top {
  width: 974px;
  height: 46px;
  border: 1px solid #e6e6e6;
  background-color: #f8f8f8;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.result-top li {
	float: left;
	height: 46px;
	line-height: 46px;
	position: relative;
}

.result-top li:hover {
	color: #ff600a;
}

.result-top .result-comprehensive {
	padding: 0 24px;
	cursor: pointer;
}

.result-top .result-sale {
	padding: 0 38px 0 24px;
	cursor: pointer;
}

.result-top .result-price {
	padding: 0 38px 0 24px;
	margin-right: 8px;
	cursor: pointer;
}

.result-top .comprehensive {
	color: #ff600a;
	border-right: 1px solid #e6e6e6;
	background-color: #fff;
}

.result-top .sale {
	color: #ff600a;
	border-left: 1px solid #e6e6e6;
	border-right: 1px solid #e6e6e6;
	background-color: #fff;
}

.result-top .sale.desc i {
	background: url(../assets/images/search/icon_arrow_down_hover.png) no-repeat;
}

.result-top .sale.asc i {
	background: url(../assets/images/search/icon_arrow_up_hover.png) no-repeat;
}

.result-top .price {
	color: #ff600a;
	border-left: 1px solid #e6e6e6;
	border-right: 1px solid #e6e6e6;
	background-color: #fff;
}

.result-top .price.desc i {
	background: url(../assets/images/search/icon_arrow_down_hover.png) no-repeat;
}

.result-top .price.asc i {
	background: url(../assets/images/search/icon_arrow_up_hover.png) no-repeat;
}

.result-top .desc i {
	display: block;
	width: 10px;
	height: 12px;
	position: absolute;
	top: 18px;
	right: 18px;
	background: url(../assets/images/search/icon_arrow_down_normal.png) no-repeat;
}

.result-top .desc:hover i {
	background: url(../assets/images/search/icon_arrow_down_hover.png) no-repeat;
}

.result-top .asc i {
	display: block;
	width: 10px;
	height: 12px;
	position: absolute;
	top: 18px;
	right: 18px;
	background: url(../assets/images/search/icon_arrow_up_normal.png) no-repeat;
}

.result-top .asc:hover i {
	background: url(../assets/images/search/icon_arrow_up_hover.png) no-repeat;
}

.result-top .result-input-group {
	font-size: 0;
	padding: 0 15px;
	border-left: 1px solid transparent;
	border-right: 1px solid transparent;
	position: relative;
}

.result-top .result-input-group:after {
	content: '';
	display: block;
	width: 4px;
	height: 0;
	border-top: 1px solid #a5a5a5;
	position: absolute;
	top: 23px;
	left: 76px;
}

.result-top .result-input-focus {
	background-color: #fff;
	box-shadow: 0 3px 6px 0 rgba(141,141,141,0.3);
	border-left: 1px solid #e6e6e6;
	border-right: 1px solid #e6e6e6;
}

.result-input-group .result-input {
	width: 52px;
	height: 24px;
	padding: 0 5px;
	color: #333;
	font-size: 12px;
	line-height: 22px;
	box-sizing: border-box;
	border: 1px solid #e0e0e0;
}

.result-input-right {
	margin-left: 20px;
}

.result-input-group .result-btn {
	width: 52px;
	height: 24px;
	border: none;
	background-color: #ff600a;
	font-size: 12px;
	color: #fff;
	cursor: pointer;
	margin-left: 16px;
}

.result-input-group .result-btn:hover {
	background-color: #ff3c00;
}

.result-input-group .result-btn:active {
	background-color: #e83700;
}

.result-list{
  width: 976px;
  overflow: hidden;
}


.search-item {
  width: 229px;
  float: left;
  box-sizing: border-box;
  padding: 21px 22px 21px 21px;
  border: 1px solid #e6e6e6;
  margin: 24px 20px 0 0;
  cursor: pointer;
}

.search-item:hover {
	border: 1px solid #ff600a;
}

.search-no-right {
	margin-right: 0;
}

.pager {
	margin-top: 60px;
}

.search-null {
	margin-top: 100px;
	padding-bottom: 40px;
}

.search-null-img {
	width: 300px;
	height: 200px;
	margin: 0 auto;
	background: url(../assets/images/search/illustration_search.png) no-repeat;
}

.search-null-title {
	height: 28px;
	line-height: 28px;
	text-align: center;
	font-size: 20px;
	color: #666;
	font-weight: bold;
	margin-top: 20px;
}

.search-null-title span {
	color: #ff600a;
}

.search-null-tip {
	height: 20px;
	line-height: 20px;
	text-align: center;
	font-size: 14px;
	color: #a5a5a5;
	margin-top: 16px;
}

.guess {
	margin-top: 60px;
}

.recommend {
	margin-top: 100px;
}

.loading {
  margin: 200px 0;
}

.list-loading {
  margin-top: 100px;
}

.search-price {
  width: 500px;
  margin: 160px auto 0;
}

.search-price-img {
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: url(../assets/images/search/illustration_search.png) no-repeat;
}
.result-input-group .not-allow {
  cursor: not-allowed;
}
</style>
